<template>
  <el-dialog
      v-model="visible"
      :title="user?.id ? t('编辑') : t('添加')"
      width="500px"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item :label="t('用户名')" required>
        <el-input v-model="form.username" autocomplete="new-username"></el-input>
      </el-form-item>
      <el-form-item :label="t('密码')" v-if="!user?.id" required>
        <el-input v-model="form.password" :type="showPassword ? 'text' : 'password'" autocomplete="new-password">
          <template #suffix>
            <el-icon class="cursor-pointer" @click="showPassword = !showPassword">
              <View v-if="showPassword"/>
              <Hide v-else/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="t('角色')" required>
        <el-select v-model="form.role" class="w-full">
          <el-option v-for="role in roles" :key="role" :label="role" :value="role"/>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">{{ t('取消') }}</el-button>
      <el-button type="primary" @click="submit">{{ t('保存') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, watch} from 'vue'
import {ElMessage} from "element-plus";
import {Hide, View} from '@element-plus/icons-vue'
import {useI18n} from "vue-i18n";

const {t} = useI18n()
const props = defineProps({
  modelValue: Boolean,
  user: Object,
})
const roles=["ADMIN", "EDITOR", "VIEWER"]
const emit = defineEmits(['update:modelValue', 'submit'])

const visible = ref(false)
const showPassword = ref(false)
const form = ref({
  username: '',
  password: '',
  role: []
})

watch(() => props.modelValue, (val) => {
  visible.value = val
})

watch(visible, (val) => {
  emit('update:modelValue', val)
  if (val && props.user) {
    form.value = {
      username: props.user.username,
      password: '',
      role: props.user.role
    }
  } else if (val) {
    form.value = {
      username: '',
      password: '',
      role: []
    }
  }
})

const submit = () => {
  if (!form.value.username) {
    ElMessage.error('请填写完整信息')
    return
  }

  const submitData = { ...form.value }
  if (props.user?.id) {
    submitData.id = props.user.id
  }

  emit('submit', submitData)
  visible.value = false
}
</script>